package com.mall.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mall.dao.mapper.AddressMapper;
import com.mall.model.Address;
import com.mall.model.AddressExample;

@Service
public class AddressService {
	@Autowired
	private AddressMapper addressMapper;

	public AddressMapper getAddressMapper() {
		return addressMapper;
	}

	public void setAddressMapper(AddressMapper addressMapper) {
		this.addressMapper = addressMapper;
	}

	/**
	 * 获取地址,如果userId不为空就根据用户id获取
	 *
	 * @dagewang 2017年8月17日
	 */
	public List<Address> get(Integer id, Integer userId) {
		List<Address> list = new ArrayList<Address>();
		if (userId != null) {
			AddressExample ex = new AddressExample();
			ex.createCriteria().andUseridEqualTo(userId);
			list = addressMapper.selectByExample(ex);
		} else {
			Address a = addressMapper.selectByPrimaryKey(id);
			list.add(a);
		}

		return list;
	}

	/**
	 * 根据userID取地址集合
	 *
	 * @dagewang 2017年9月13日
	 */
	public List<Address> getByUserId(Integer id) throws Exception {
		AddressExample ex = new AddressExample();
		ex.createCriteria().andUseridEqualTo(id);
		return addressMapper.selectByExample(ex);
	}

	/**
	 * 修改地址和默认状态
	 * 
	 * @param did
	 *
	 * @dagewang 2017年9月13日
	 */
	public Integer update(Address address, Integer did) throws Exception {
		Integer updateByPrimaryKeySelective = null;
		if (address.getDefaults() != null) {
			Address a = new Address();
			a.setId(did);
			a.setDefaults(0);
			a.setUdate(new Date());
			int r = addressMapper.updateByPrimaryKeySelective(a);
			if (r == 1) {
				return addressMapper.updateByPrimaryKeySelective(address);
			}
		} else {
			address.setUdate(new Date());
			updateByPrimaryKeySelective = addressMapper.updateByPrimaryKeySelective(address);
		}
			return updateByPrimaryKeySelective;
	}
	/**
	 * 保存地址
	 * @param size 
	 *
	 *@dagewang 2017年9月13日
	 */
	public Address save(Address address,Integer id, int size)throws Exception {
		address.setUserid(id);
		address.setCdate(new Date());
		if(size==0){
			address.setDefaults(1);
		}else{
			address.setDefaults(0);
		}
		int insert =0;
		try {
			insert=addressMapper.insert(address);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(insert==0){
			return null;
		}
		return address;
	}

}
